package device_ctr;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.util.Log;

public class Dev_comu {
	private String device_name;
	public String getDevice_name() {
		return device_name;
	}
	public String getHtml_msg() {
		return html_msg;
	}
	public void setDevice_name(String device_name) {
		this.device_name = device_name;
	}
	public boolean isHasFinished() {
		return HasFinished;
	}
	private boolean HasFinished;
	private String cmd_txt;
	private String html_msg;
	private String De_IP="192.168.11.254";
	private int De_PortNo=8080;
	DatagramSocket ds = null;  
    DatagramPacket dp,dp2 = null;
	public Dev_comu(String dev_name) {
		super();
		// TODO Auto-generated constructor stub
		this.device_name=dev_name;
        try {  
            this.ds = new DatagramSocket(8080); 
            ds.setSoTimeout(1000);
            this.HasFinished=false;
    		html_msg="";
        } catch (SocketException e) {  
        	// TODO Auto-generated catch block  
            Log.e("UDP", e.toString());
            cmd_para cmd_builer = new cmd_para();
    		html_msg=cmd_builer.cmd2txt("ER",e.toString() );
    		this.HasFinished=true;
        } 
	}
	public String send_msg(String msg,int new_pass){
		TinyEncryptor jiami=new TinyEncryptor();
		if (new_pass>0){
			jiami.set_new_pass(new_pass);
		}
		else{
			jiami.reset_new_pass();
		}
		String msg_code=jiami.Str_Code(msg);
		this.cmd_txt="!" + msg_code + get_jiaoyan(msg_code) + "*";
		Connect_server comu2server=new Connect_server();
		comu2server.start(); 
		while(HasFinished==false){
			;
		}
		return html_msg;
	}
	public String jie_mi(String msg,int new_pass){
		int str_start=msg.indexOf("!");
		int str_end=msg.indexOf("*");
		
		if ((str_start>-1 && str_end>str_start)==true){
			String you_xiao=msg.substring(str_start+1, str_end);
			if (you_xiao.length()%8==2){
				String str_need_solve=you_xiao.substring(0,you_xiao.length()-2);
				if (you_xiao.substring(you_xiao.length()-2).equals(get_jiaoyan(str_need_solve))){
					TinyEncryptor jiami=new TinyEncryptor();
					if (new_pass>0){
						jiami.set_new_pass(new_pass);
					}
					else{
						jiami.reset_new_pass();
					}
					String msg_need_return=jiami.Str_DeCode(str_need_solve);
					return msg_need_return;
				}
				else{
					return "jiaoyancuowu";
				}
			}
			else
				return "length error";
		}
		else{
			return "fomat error";
		}
	}
	private static String get_jiaoyan(String ll){
		int i=0;
		int sum=0;
		int temp;
		try {
			for(i=0;i<ll.length();i++)
			{
				temp=Integer.valueOf(ll.substring(i, i+1),16);
				if (temp<10){
					sum=sum+48+temp;
				}
				if (temp>=10){
					sum=sum+55+temp;
				}
			}
			sum=sum%256;
			sum=255-sum;
			return Integer.toHexString(sum).toUpperCase();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
	}
	private class cmd_para{
		private String cmd_type="";
		public String getCmd_type() {
			return cmd_type;
		}
		public void setCmd_type(String cmd_type) {
			this.cmd_type = cmd_type;
		}
		public String getCmd_msg() {
			return cmd_msg;
		}
		public void setCmd_msg(String cmd_msg) {
			this.cmd_msg = cmd_msg;
		}
		public String getCmd_txt() {
			return cmd_txt;
		}
		public void setCmd_txt(String cmd_txt) {
			this.cmd_txt = cmd_txt;
		}
		private String cmd_msg="";
		private String cmd_txt="";
		public String cmd2txt(String cmd,String msg){
			String a="";
			a="!" + cmd + msg+"*";
			//return a;
			return cmd;
		}
	}
	class Connect_server extends  Thread {
		@Override
	    public void run() {
	        tongxin();
		}
		private void tongxin(){
			if (HasFinished==false){
				byte [] buf = cmd_txt.getBytes();  
				int length = buf.length; 
				InetSocketAddress remoteAddress2 = new InetSocketAddress(De_IP,De_PortNo);

				try {
					dp = new DatagramPacket(buf,length,remoteAddress2);
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
	            try {
	                ds.send(dp);  
	            } catch (IOException e) {  
	                // TODO Auto-generated catch block  
	                e.printStackTrace(); 
	                cmd_para cmd_builer = new cmd_para();
	        		html_msg=cmd_builer.cmd2txt("ER",e.toString());
	        		HasFinished =true;
	            }
	            html_msg="";
	            while (HasFinished==false && html_msg.contains("*")==false){
	            	
	            	byte [] data = new byte[1024];  
		            dp2 = new DatagramPacket(data, data.length); 
		            
		            try {  
		            	ds.receive(dp2);  
		            } catch (IOException e) {  
		                // TODO Auto-generated catch block  
		                e.printStackTrace(); 
		        		HasFinished =true;
		            } 
		            
		            String str_temp="";
		            try {  
		            	str_temp=new String(dp2.getData(),0,dp2.getLength(),"utf-8");  
		            } catch (UnsupportedEncodingException e) {  
		                // TODO Auto-generated catch block  
		                e.printStackTrace();		  
		        		HasFinished =true;
		            }
		            html_msg=html_msg+str_temp;
	            }
	            //System.out.println("IP: " + dp2.getSocketAddress());
	            HasFinished =true;
	            ds.close();
			}
		}
	}

}
	
	